package com.laikan.reader.bookstore.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookreader.activity.BookDesActivity;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.CateRankAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.More;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.CircleProgressBar;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

/**
 * 书籍列表
 *
 * @author Administrator
 */
public class CateRankActivity extends BasicActivity {

    private int width;
    private ArrayList<More> moreList;
    private HashSet mBookIdList = new HashSet();
    private CateRankAdapter mAdapter;
    private BaseDataBean<BaseListDataBean<More>> result;
    private ListView rankcate_list;
    private boolean IsHead = false;
    private TouchSwipeRefreshLayout mCommentSwipeRefresh;
    private String url;
    private String title;
    private boolean isShowOrder;

    /**
     * 标题栏
     */
    private TextView title_tv;
    private ImageView back_tv;
    private RelativeLayout back_layout,common_loaddata_notice;
    private TextView common_prompt_content,common_refresh_net;
    private CircleProgressBar comon_bgbar_loading;
    private long mLoadDelaynternalTime;
    private Drawable drawable_back_tv;
    private String mode;
    private boolean isFromBasicWebView;

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_cate_rank1);
        WindowManager window = this.getWindowManager();
        width = window.getDefaultDisplay().getWidth();
        mCommentSwipeRefresh = (TouchSwipeRefreshLayout)findViewById(R.id.common_swiperefresh);
        mCommentSwipeRefresh.setColorSchemeResources(R.color.C_66ccdd);
        rankcate_list = (ListView)findViewById(R.id.rankcate_list);
        title_tv = (TextView)findViewById(R.id.tv_title);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        comon_bgbar_loading = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);
        mCommentSwipeRefresh.setChildView(rankcate_list);
    }

    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        moreList = new ArrayList<More>();
        Intent intent = getIntent();
        String action = intent.getAction();

        if("from_basic_web_view".equals(action)){
            //新版精选
            isFromBasicWebView = true;
            title = intent.getStringExtra("title");
            url = intent.getStringExtra("rankUrl");
            isShowOrder = intent.getBooleanExtra("isShowOrder",false);//是否排序
        }else{
            //原版精选传的值
            isFromBasicWebView = false;
            url = intent.getStringExtra("mHtmlUrl");
            title = intent.getStringExtra("title");
            mode = intent.getStringExtra("mode");
        }

        title_tv.setText(this.title);
        mAdapter = new CateRankAdapter(mContext, moreList);
        rankcate_list.setAdapter(mAdapter);

        if(ActivityUitl.isNetworkAvailable(mContext)){
            if(isFromBasicWebView){
                getData(true);

            }else {
                if (mode.equals("more")) {
                    getData(true);
                }else if (mode.equals("special")) {
                    getDateSpecial();
                }
            }
        }else{
            common_loaddata_notice.setVisibility(View.VISIBLE);
            mCommentSwipeRefresh.setVisibility(View.GONE);
            comon_bgbar_loading.setVisibility(View.INVISIBLE);
            common_prompt_content.setText(R.string.laikan_network_anomaly);
        }


    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        rankcate_list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                int subscript = 0;
                if (IsHead) {
                    if (arg2 != 1) {
                        subscript = arg2 - 1;
                    }else {
                        return;
                    }
                }else {
                    subscript = arg2;
                }

                Intent intent = new Intent();
                intent.setClass(mContext, BookDesActivity.class);
                intent.putExtra("bookId", moreList.get(subscript).getBookId());
                startActivity(intent);

            }
        });

        // 上拉加载 下拉刷新
        mCommentSwipeRefresh.setOnRefreshListener(new TouchSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCommentSwipeRefresh.setLoading(false);
                getData(false);
            }
        });
    }

    private void getData(boolean isload) { //这个接口不知道是否有问题
        if(isload){
            showDialog();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("mark", "");
        String[] Url = url.split("=");

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mCommentSwipeRefresh.setRefreshing(false);
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<BaseDataBean<BaseListDataBean<More>>>() {
                    }.getType();
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
//                            ToastMgr.showShortToast(result.getError_msg());
                            showErrorView(1);
                        }else {
                            // 下拉刷新
                            common_loaddata_notice.setVisibility(View.GONE);
                            mCommentSwipeRefresh.setVisibility(View.VISIBLE);
                            mAdapter.setDatas(updateListData(result.getData().getData()));
                        }
                    }else {
                        showErrorView(1);
                    }
                }catch (Exception e) {
                    showErrorView(1);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mCommentSwipeRefresh.setRefreshing(false);
                showErrorView(2);
                KLog.e("网络不给力，请重试。07");
            }

            @Override
            public void onFinish() {
                dismissDialog();
                mCommentSwipeRefresh.setRefreshing(false);
            }
        };

        Requester requester = new Requester();
        requester.setUrl(url);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpGetRequest(url, null, null, requestListener);
    }

    /**
     *  设置错误布局的显示与隐藏
     * @param type  type为1  数据加载失败，type 为2  网络异常
     */
    String showContent;
    private void settingShowOrHide(int type){
        if(type == 1){
            showContent = getString(R.string.laikan_data_load_failed);
        }else if(type == 2){
            showContent = getString(R.string.laikan_network_anomaly);
        }
        common_loaddata_notice.setVisibility(View.VISIBLE);
        mCommentSwipeRefresh.setVisibility(View.GONE);
        common_prompt_content.setText(showContent);
    }
    /**
     * @param type 为1，数据加载失败，为2 网络异常
     */
   private void showErrorView(int type){
       settingShowOrHide(type);
       closeDelayLoading(System.currentTimeMillis());
   }

    private ArrayList<More> updateListData(ArrayList<More> list) {
        ArrayList<More> refreshList = new ArrayList<More>();
        for (int i = 0; i < list.size(); i++) {
            if (!mBookIdList.contains(list.get(i).getBookId())) {
                mBookIdList.add(list.get(i).getBookId());
                refreshList.add(list.get(i));
            }
        }
        refreshList.addAll(moreList);
        moreList.clear();
        moreList.addAll(refreshList);
        if(refreshList!=null){
            refreshList.clear();
        }
        refreshList = null;
        return moreList;
    }

    private void getDateSpecial() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("mark", "");
        String[] Url = url.split("=");

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mCommentSwipeRefresh.setRefreshing(false);
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<BaseDataBean<BaseListDataBean<More>>>() {
                    }.getType();
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
//                            ToastMgr.showShortToast(result.getError_msg());
                            showErrorView(1);
                        }else {
                            // TODO 在这里判断是否允许回复
                            // 下拉刷新
                            common_loaddata_notice.setVisibility(View.GONE);
                            mCommentSwipeRefresh.setVisibility(View.VISIBLE);
                            mAdapter.setDatas(updateListData(result.getData().getData()));
                            if (result.getData().getPicture() != null && (!result.getData().getPicture().equals("")) && result.getData().getIntroduce() != null && (!result.getData().getIntroduce().equals(""))) {
                                IsHead = true;
                                View v = View.inflate(mContext, R.layout.special_head, null);
                                final ImageView image = (ImageView)v.findViewById(R.id.special_image);
                                TextView special_text = (TextView)v.findViewById(R.id.special_text);
                                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)image.getLayoutParams();
                                params.height = width / 3;
                                image.setLayoutParams(params);
                                Bitmap bim = PublicUtil.readBitMap(mContext, R.drawable.special_reco);
                                image.setImageBitmap(Bitmap.createScaledBitmap(bim, width, width / 3, true));
                                image.setImageURI(Uri.parse(result.getData().getPicture()));
                                //                                    imageLoader.loadImage(result.getData().getPicture(), new ImageLoadingListener() {
                                //
                                //                                        @Override
                                //                                        public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
                                //
                                //                                            image.setImageBitmap(Bitmap.createScaledBitmap(arg2, width, width / 3, true));
                                //                                        }
                                //
                                //                                    });
                                special_text.setText(result.getData().getIntroduce());
                                rankcate_list.addHeaderView(v);
                            }
                        }
                    }else {
                        showErrorView(1);
                    }
                }catch (Exception e) {
                    showErrorView(1);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mCommentSwipeRefresh.setRefreshing(false);
                showErrorView(2);
                KLog.e("网络不给力，请重试。08");
            }

            @Override
            public void onFinish() {
                mCommentSwipeRefresh.setRefreshing(false);
            }
        };

        Requester requester = new Requester();
        requester.setUrl(url);
//        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpGetRequest(url, null, null, requestListener);

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        // MobclickAgent.onPause(this);
        SPUtil.putBoolean("Single_click", false);
    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.back_layout:
                finish();
            case R.id.common_refresh_net:
                comon_bgbar_loading.setVisibility(View.VISIBLE);
                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                if(ActivityUitl.isNetworkAvailable(CateRankActivity.this)){
                    if(isFromBasicWebView){
                        getData(false);
                    }else {
                        if (mode.equals("more")) {
                            getData(false);
                        }else if (mode.equals("special")) {
                            getDateSpecial();
                        }
                    }
                }else{
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
            default:
                break;
        }
    }
    private void closeDelayLoading(long currenttime){
        if(currenttime < mLoadDelaynternalTime){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestDataResultHandle();
                }
            },1000);
        }else{
            requestDataResultHandle();
        }
    }
    private void requestDataResultHandle(){
        comon_bgbar_loading.setVisibility(View.INVISIBLE);
        common_refresh_net.setOnClickListener(CateRankActivity.this);
        common_loaddata_notice.setVisibility(View.VISIBLE);
        mCommentSwipeRefresh.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
